<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Cms_Errmsg;
use App\Third\Wechat;
use Illuminate\Http\Request;
use GuzzleHttp;
class WxController extends Controller
{
    public function wx_token(Request $request)
    {
        // 验证消息来自微信服务器
        $method = $request->method();

        if($method=='GET'){
            $data = $request->input();
            // 验证签名
            if ($this->checkSignature($data)) {
                ob_end_clean(); //必须清空缓冲区
            }else{
                // 签名验证失败，返回错误信息
                return 'Invalid signature';
            }
        }

        if($method=='POST'){
            // 事件处理    关注/取消事件等
            $data = file_get_contents("php://input");

            if (!empty($data)) {
                $postObj = simplexml_load_string($data);
                Cms_Errmsg::create(['errMsg'=>json_encode(['msg' => $postObj])]);
                // 微信消息类型
                $RX_TYPE = trim($postObj->MsgType);
                switch ($RX_TYPE) {
                    case "text":
                        Cms_Errmsg::create(['errMsg'=>json_encode(['msg' => $RX_TYPE])]);
                        // 文本消息
                        $resultStr = $this->handleText($postObj);
                        break;
                    default:
                        $resultStr = "Unknow msg type: " . $RX_TYPE;
                        break;
                }
                echo $resultStr;
            }else{
                Cms_Errmsg::create(['errMsg'=>json_encode(['msg' => 'else'])]);
                echo "";
                exit;
            }
        }
    }

    /**
     * 验证签名
     */

    public function checkSignature($data)
    {
        $signature = $data['signature'];
        $timestamp = $data['timestamp'];
        $nonce = $data['nonce'];
        $token = config('wx.token');

        $array = array($timestamp, $nonce, $token);

        sort($array);
        //排序之后的数据拼接好使用sha1加密
        $tmpstr = implode('', $array);
        $tmpstr = sha1($tmpstr);
        //将加密后的字符串与singature进行对比，判断是否来自微信请求
        if ($tmpstr == $signature) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 构造回复的 XML 消息
     */
    public function handleText($postObj)
    {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";
        switch ($keyword) {
            case '价格':
                $contentStr = '价格详情请咨询400088569';
                return sprintf($textTpl, $fromUsername, $toUsername, $time, $postObj->MsgType, $contentStr);
            case '你好':
                $contentStr = '欢迎关注我们';
                return sprintf($textTpl, $fromUsername, $toUsername, $time, $postObj->MsgType, $contentStr);
            default:
                $contentStr = 'Unknown keyword';
                return sprintf($textTpl, $fromUsername, $toUsername, $time, $postObj->MsgType, $contentStr);

        }
    }

    public function defined_button(Request $request)
    {
        $menuData = $request->input('menuData');
        $access_token = Wechat::getWechatToken();
        $http = new GuzzleHttp\Client();
        $http->request('GET', 'https://api.weixin.qq.com/cgi-bin/menu/delete?', [
            'query' => ['access_token' => $access_token],
        ]);
        $menuData = [
            'button' => [
                [
                    'type' => 'click',
                    'name' => '今日歌曲',
                    'key' => 'V1001_TODAY_MUSIC'
                ],
                [
                    'name' => '菜单',
                    'sub_button' => [
                        [
                            'type' => 'view',
                            'name' => '搜索',
                            'url' => 'http://www.soso.com/'
                        ],
                        [
                            'type' => 'view',
                            'name' => '视频',
                            'url' => 'http://v.qq.com/'
                        ],
                        [
                            'type' => 'click',
                            'name' => '赞一下我们',
                            'key' => 'V1001_GOOD'
                        ]
                    ]
                ]
            ]
        ];
        $jsonData = [
            'body' => json_encode($menuData,JSON_UNESCAPED_UNICODE),
            'headers' => ['content-type' => 'application/json']
        ];
        $response = $http->request('POST', 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token, $jsonData);
        return json_decode($response->getBody()->getContents(), true);
    }

}
